package com.foreknow.elmboot.service.impl;


import com.foreknow.elmboot.mapper.CartMapper;
import com.foreknow.elmboot.mapper.OrderDetailetMapper;
import com.foreknow.elmboot.mapper.OrdersMapper;
import com.foreknow.elmboot.po.Cart;
import com.foreknow.elmboot.po.OrderDetailet;
import com.foreknow.elmboot.po.Orders;
import com.foreknow.elmboot.service.OrdersService;
import com.foreknow.elmboot.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private OrderDetailetMapper orderDetailetMapper;
    @Override
    public int createOrdersService(Orders orders) {
        //然后根据用户编号、商家编号从购物车表中查询所有数据
        Cart cart = new Cart();
        cart.setBusinessId(orders.getBusinessId());
        cart.setUserId(orders.getUserId());
        List<Cart> cartList = cartMapper.listCartDao(cart);
        //根据用户编号、商家编号、订单总金额、送货地址编号向订单表中添加一条记录，并获取自动生成的订单编号
        orders.setOrderDate(CommonUtil.getCurrentDate());
        orders.setOrderState(0);
        ordersMapper.saveOrdersDao(orders);
        //将购物车表中的数据和订单编号导入明细中
        List<OrderDetailet> orderDetailets = new ArrayList<>();
        for (int i = 0; i < cartList.size(); i++) {
            OrderDetailet orderDetailet = new OrderDetailet();
            orderDetailet.setOrderId(orders.getOrderId());
            orderDetailet.setFoodId(cartList.get(i).getFoodId());
            orderDetailet.setQuantity(cartList.get(i).getQuantity());
            orderDetailets.add(orderDetailet);
        }
        //批量添加订单明细
        orderDetailetMapper.saveOrderDetailDao(orderDetailets);
        //根据用户编号、商家编号删除购物车表中的数据
        cartMapper.removeCartDao(cart);
        return orders.getOrderId();
    }

    @Override
    public Orders getOrdersByIdService(Integer orderId) {
        return ordersMapper.getOrdersByIdDao(orderId);
    }

    @Override
    public List<Orders> listOrdersByUserIdService(String userId) {
        return ordersMapper.listOrdersByUserIdDao(userId);
    }
}
